<template>
  <div
    class="form-item-readonly"
    :class="{
      'form-item-whole-line': _info.width === 100
    }"
  >
    <span class="form-label-readonly" :style="`color:${_info.name_color}`">
      {{ _info.name }}
      <zx-header-tip v-if="_info.tips">
        <div v-html="_info.tips" />
      </zx-header-tip>
      ：
    </span>
    <span
      class="form-value-readonly"
      v-loading="selectLoading"
      :element-loading-spinner="loadingSpinner"
      element-loading-svg-view-box="0,0, 1024, 1024"
      :style="`text-align:${_info.align};`"
    >
      <!-- 图片 -->
      <span v-if="_info.field_type === 'upload'">
        <span v-if="!showImgs.length">{{ DEFAULT_TEXT }}</span>
        <div v-else style="display: flex; align-items: flex-start">
          <zx-image :urls="showImgs" width="100px" height="100px" />
          <el-button
            v-if="
              _info.has_btn &&
              showImgs.length &&
              _info.btn_action === 'download'
            "
            type="primary"
            link
            class="ml-15"
            style="line-height: 15px"
            :loading="downLoading"
            @click="download"
          >
            {{ _info.btn_text }}
          </el-button>
        </div>
      </span>

      <!-- 其他文本类  -->
      <span v-else :style="`color:${_info.value_color};`">
        {{ showText ?? DEFAULT_TEXT }}
      </span>

      <!-- 单位 -->
      <span
        v-if="_info.unit && showText != undefined"
        :style="`color:${_info.unit_color}`"
      >
        {{ _info.unit }}
      </span>
      <!-- 更新Token按钮 -->
      <el-button
        type="primary"
        link
        class="refresh-btn"
        v-if="_info.has_btn && _info.btn_action === 'refresh_token'"
        @click="topExpose.events?.refreshEvent?.()"
      >
        <el-icon><Refresh /></el-icon>
      </el-button>
      <!-- 分配个号按钮 -->
      <el-button
        v-if="_info.has_btn && _info.btn_action === 'fill_value'"
        type="primary"
        class="fill-btn"
        size="small"
        :loading="fillLoading"
        @click="clickFill"
      >
        {{ _info.btn_text }}
      </el-button>
    </span>
  </div>
</template>

<script setup>
import { downloadImgs, formatNumberWithCommas } from '@/utils';
import { DEFAULT_TEXT, IMG_URL } from '@/utils/const';
import {
  getInfo,
  getRules,
  isArray,
  flatOptionsObj,
  fillValue
} from '../const';
import {
  searchDynamicForm,
  searchPlatformDynamicForm
} from '@/api/dynamic-form';
import { loadingSpinner } from '@/assets/js/loadingIcon.js';

const props = defineProps({
  formInfo: {
    type: Object,
    default: () => {}
  },
  value: {
    type: String,
    default: ''
  },
  isEach: {
    type: Boolean,
    default: false
  },
  topExpose: {
    type: Object,
    default: () => {}
  }
});

const _info = computed(() => getInfo(props.formInfo));
const _rules = computed(() => getRules(props.formInfo));
const downLoading = ref(false);
const fillLoading = ref(false);

function clickFill() {
  fillValue({ _info: _info.value, fillLoading, topExpose: props.topExpose });
}

// 图片显示
const showImgs = computed(() => {
  let value = props.isEach ? props.value : _info.value.value;
  if (isArray(value)) {
    return value.filter((item, index) => {
      if (!item) return false;
      value[index] = IMG_URL(item);
      return true;
    });
  }
  if (value) return [IMG_URL(value)];
  return [];
});

// 图片下载
function download() {
  downloadImgs(showImgs.value, _info.value.name, downLoading);
}

// 下拉处理
const optionsTypes = ['select', 'cascader', 'radio', 'checkbox'];
const optionList = ref([]);
const selectLoading = ref(false);
function getOptions() {
  if (_info.value.options?.length) {
    optionList.value = _info.value.options;
    return;
  }
  selectLoading.value = true;
  const api = {
    company: searchDynamicForm,
    platform: searchPlatformDynamicForm
  }[props.topExpose.form_role];
  api({
    form_uni_key: props.topExpose.form_uni_key,
    field_name: _info.value.field,
    values: props.topExpose.initValues()
    // search:'' // 搜索的内容 远程搜索可能会用到 目前没有远程搜索
  })
    .then(res => {
      optionList.value = res.data || [];
    })
    .finally(() => {
      selectLoading.value = false;
    });
}
if (optionsTypes.includes(_info.value.field_type)) getOptions();

// 文本显示
const showText = computed(() => {
  let value = props.isEach ? props.value : _info.value.value;

  // 全部处理成数组 和 空处理
  if (!isArray(value)) value = [value];
  value?.forEach((item, index) => {
    if (_rules.value?.decimal && item) {
      value[index] = Number(item).toFixed(_rules.value.decimal);
    }
    // 千分符处理
    if (_rules.value.thousands_separator && item) {
      value[index] = formatNumberWithCommas(item);
    }
  });
  if (
    !value.length ||
    (value.length === 1 && ['', undefined, null].includes(value[0]))
  ) {
    return undefined;
  }

  if (optionsTypes.includes(_info.value.field_type)) {
    const optionsObj = {};
    flatOptionsObj(optionList.value, optionsObj);
    const newValue = [];
    value.forEach(item => {
      if (optionsObj[item]) newValue.push(optionsObj[item]?.name);
    });
    if (!newValue.length) return undefined;
    return newValue.join('、');
  }
  return value.join('、');
});
</script>

<style lang="scss" scoped>
.fill-btn {
  transform: translateY(-2px);
  margin-left: 12px;
}
</style>
